/**
 * 客户档案管理模块 API 接口
 * @description 客户档案管理相关的所有API接口封装
 * @author CRM开发团队
 * @version 1.0.0
 */

import { request } from '@/utils/request'

// ==========================================
// 类型定义
// ==========================================

// 客户列表查询参数
export interface CustomerListQuery {
  page?: number
  pageSize?: number
  keyword?: string
  customerStatus?: string
  gender?: string
  ageMin?: number
  ageMax?: number
  healthStatus?: string
  tags?: string[]
  createdAtStart?: string
  createdAtEnd?: string
  sortBy?: string
  sortOrder?: 'asc' | 'desc'
}

// 客户基础信息
export interface CustomerBasicInfo {
  id?: number
  customerCode?: string
  customerName: string
  gender: '男' | '女'
  birthDate: string
  age?: number
  idCard: string
  primaryPhone: string
  backupPhone?: string
  wechat?: string
  qq?: string
  email?: string
  address?: string
  postalCode?: string
  emergencyContactName: string
  emergencyContactRelation: '配偶' | '子女' | '亲属' | '朋友' | '其他'
  emergencyContactPhone: string
  workStatus: '在职' | '退休' | '待业' | '其他'
  occupation?: string
  customerStatus: '有效客户' | '潜在客户' | '无效客户' | '已成交客户' | '黑名单'
  referrerInfo?: {
    referrerName?: string
    referrerPhone?: string
    referrerRelation?: '朋友推荐' | '老客户推荐' | '网络推荐' | '其他'
    referrerTime?: string
  }
  // 旅游偏好基础信息
  destinationPreference?: string[]
  budgetRange?: '经济型' | '舒适型' | '品质型' | '豪华型'
  // 扩展字段
  tags?: CustomerTag[]
  healthStatus?: '健康良好' | '健康一般' | '健康较差' | '健康很差'
  lastContactTime?: string
  lastContactAt?: string  // 别名字段，保持兼容
  monthlyContactCount?: number
  createdAt?: string
  updatedAt?: string
}

// 客户标签
export interface CustomerTag {
  id?: number
  category: '价值分类' | '服务特点' | '出行特点' | '健康状态' | '消费习惯' | '自定义'
  name: string
  value?: string
  isSystem: boolean
  createdAt?: string
}

// 旅游偏好
export interface TravelPreferences {
  budgetRange?: '经济型' | '舒适型' | '品质型' | '豪华型'
  budgetMin?: number
  budgetMax?: number
  consumptionFeatures?: string[]
  paymentPreference?: '现金支付' | '银行转账' | '微信支付' | '支付宝' | '刷卡'
  domesticRegions?: string[]
  internationalRegions?: string[]
  landscapePreferences?: string[]
  climatePreferences?: string[]
  seasonPreferences?: string[]
  monthPreferences?: number[]
  durationPreference?: '短途' | '中途' | '长途' | '超长'
  transportPreferences?: string[]
  accommodationStandard?: '经济型酒店' | '舒适型酒店' | '高档酒店' | '度假村' | '民宿客栈'
}

// 健康信息
export interface HealthInfo {
  healthStatus: '健康良好' | '健康一般' | '健康较差' | '健康很差'
  mobilityAbility: '行动自如' | '轻微受限' | '需要辅助' | '轮椅出行'
  chronicDiseases?: string[]
  cardiovascularDiseases?: string[]
  endocrineDiseases?: string[]
  respiratoryDiseases?: string[]
  musculoskeletalDiseases?: string[]
  otherDiseases?: string
  medicationInfo?: string
  dietaryRestrictions?: string[]
  insuranceInfo?: string
}

// 家庭信息
export interface FamilyInfo {
  maritalStatus?: '已婚' | '丧偶' | '离异' | '未婚'
  spouseInfo?: {
    spouseName?: string
    spousePhone?: string
    spouseAge?: number
    spouseTravelTogether?: '经常同行' | '偶尔同行' | '从不同行'
  }
  childrenInfo?: Array<{
    name: string
    phone: string
    relationshipCloseness: '关系密切' | '关系一般' | '关系疏远'
    travelAttitude: '支持' | '中立' | '反对'
  }>
  decisionPattern?: '自主决策' | '咨询决策' | '共同决策' | '代为决策'
  influenceFactors?: string[]
}

// 客户完整信息
export interface CustomerDetail {
  basicInfo: CustomerBasicInfo
  tags: CustomerTag[]
  travelPreferences?: TravelPreferences
  healthInfo?: HealthInfo
  familyInfo?: FamilyInfo
  metadata: {
    createdAt: string
    updatedAt: string
    createdBy: number
    updatedBy: number
  }
}

// 创建客户请求
export interface CreateCustomerRequest {
  basicInfo: Omit<CustomerBasicInfo, 'id' | 'customerCode' | 'age'>
  tags?: Array<Pick<CustomerTag, 'category' | 'name' | 'value'>>
}

// 更新客户请求
export interface UpdateCustomerRequest {
  [key: string]: any
  changeReason?: string
}

// 操作记录
export interface OperationLog {
  id: number
  tableName: string
  operationType: 'CREATE' | 'UPDATE' | 'DELETE' | 'VIEW'
  fieldName?: string
  oldValue?: string
  newValue?: string
  changeReason?: string
  ipAddress?: string
  createdAt: string
  createdBy: {
    id: number
    name: string
    role: string
  }
}

// 统计数据
export interface CustomerStatistics {
  totalCustomers: number
  customerStatusDistribution: Record<string, number>
  ageDistribution: Record<string, number>
  genderDistribution: Record<string, number>
  healthStatusDistribution: Record<string, number>
  regionDistribution: Record<string, number>
}

// API响应基础类型
export interface ApiResponse<T = any> {
  code: number
  message: string
  data: T
  timestamp: string
  traceId?: string
}

// 分页响应
export interface PaginationResponse<T> {
  list: T[]
  pagination: {
    page: number
    pageSize: number
    total: number
    totalPages: number
  }
  summary?: Record<string, any>
}

// ==========================================
// API接口封装
// ==========================================

export class CustomerAPI {
  private baseUrl = '/api/v1/customers'

  /**
   * 获取客户列表
   */
  async getCustomerList(params: CustomerListQuery = {}): Promise<ApiResponse<PaginationResponse<CustomerBasicInfo>>> {
    return request({
      url: this.baseUrl,
      method: 'GET',
      params
    })
  }

  /**
   * 获取客户详情
   */
  async getCustomerDetail(id: number): Promise<ApiResponse<CustomerDetail>> {
    return request({
      url: `${this.baseUrl}/${id}`,
      method: 'GET'
    })
  }

  /**
   * 创建客户
   */
  async createCustomer(data: CreateCustomerRequest): Promise<ApiResponse<{ id: number; customerCode: string; customerName: string }>> {
    return request({
      url: this.baseUrl,
      method: 'POST',
      data
    })
  }

  /**
   * 更新客户信息
   */
  async updateCustomer(id: number, data: UpdateCustomerRequest): Promise<ApiResponse<{ id: number; updatedFields: string[]; updatedAt: string }>> {
    return request({
      url: `${this.baseUrl}/${id}`,
      method: 'PUT',
      data
    })
  }

  /**
   * 删除客户
   */
  async deleteCustomer(id: number, deleteReason: string): Promise<ApiResponse<{ id: number; deletedAt: string }>> {
    return request({
      url: `${this.baseUrl}/${id}`,
      method: 'DELETE',
      data: { deleteReason }
    })
  }

  /**
   * 获取客户标签
   */
  async getCustomerTags(id: number): Promise<ApiResponse<{ systemTags: Record<string, string[]>; customTags: CustomerTag[] }>> {
    return request({
      url: `${this.baseUrl}/${id}/tags`,
      method: 'GET'
    })
  }

  /**
   * 添加客户标签
   */
  async addCustomerTags(id: number, tags: Array<Pick<CustomerTag, 'category' | 'name' | 'value' | 'isSystem'>>): Promise<ApiResponse<{ addedCount: number }>> {
    return request({
      url: `${this.baseUrl}/${id}/tags`,
      method: 'POST',
      data: { tags }
    })
  }

  /**
   * 删除客户标签
   */
  async deleteCustomerTag(id: number, tagId: number): Promise<ApiResponse<{ success: boolean }>> {
    return request({
      url: `${this.baseUrl}/${id}/tags/${tagId}`,
      method: 'DELETE'
    })
  }

  /**
   * 获取旅游偏好
   */
  async getTravelPreferences(id: number): Promise<ApiResponse<TravelPreferences>> {
    return request({
      url: `${this.baseUrl}/${id}/travel-preferences`,
      method: 'GET'
    })
  }

  /**
   * 更新旅游偏好
   */
  async updateTravelPreferences(id: number, data: TravelPreferences): Promise<ApiResponse<{ success: boolean; updatedAt: string }>> {
    return request({
      url: `${this.baseUrl}/${id}/travel-preferences`,
      method: 'PUT',
      data
    })
  }

  /**
   * 获取健康信息
   */
  async getHealthInfo(id: number): Promise<ApiResponse<HealthInfo>> {
    return request({
      url: `${this.baseUrl}/${id}/health-info`,
      method: 'GET'
    })
  }

  /**
   * 更新健康信息
   */
  async updateHealthInfo(id: number, data: HealthInfo & { changeReason?: string }): Promise<ApiResponse<{ success: boolean; updatedAt: string }>> {
    return request({
      url: `${this.baseUrl}/${id}/health-info`,
      method: 'PUT',
      data
    })
  }

  /**
   * 获取家庭信息
   */
  async getFamilyInfo(id: number): Promise<ApiResponse<FamilyInfo>> {
    return request({
      url: `${this.baseUrl}/${id}/family-info`,
      method: 'GET'
    })
  }

  /**
   * 更新家庭信息
   */
  async updateFamilyInfo(id: number, data: FamilyInfo): Promise<ApiResponse<{ success: boolean; updatedAt: string }>> {
    return request({
      url: `${this.baseUrl}/${id}/family-info`,
      method: 'PUT',
      data
    })
  }

  /**
   * 获取操作记录
   */
  async getOperationLogs(id: number, params: {
    page?: number
    pageSize?: number
    operationType?: string
    tableName?: string
    dateStart?: string
    dateEnd?: string
  } = {}): Promise<ApiResponse<PaginationResponse<OperationLog>>> {
    return request({
      url: `${this.baseUrl}/${id}/operation-logs`,
      method: 'GET',
      params
    })
  }

  /**
   * 获取客户统计概览
   */
  async getStatisticsOverview(): Promise<ApiResponse<CustomerStatistics>> {
    return request({
      url: `${this.baseUrl}/statistics/overview`,
      method: 'GET'
    })
  }

  /**
   * 获取客户趋势分析
   */
  async getStatisticsTrends(params: {
    period?: 'daily' | 'weekly' | 'monthly'
    startDate?: string
    endDate?: string
    dimension?: string
  } = {}): Promise<ApiResponse<any>> {
    return request({
      url: `${this.baseUrl}/statistics/trends`,
      method: 'GET',
      params
    })
  }

  /**
   * 批量导入客户
   */
  async batchImport(file: File, template: string): Promise<ApiResponse<{ successCount: number; failedCount: number; errors: any[] }>> {
    const formData = new FormData()
    formData.append('file', file)
    formData.append('template', template)

    return request({
      url: `${this.baseUrl}/batch/import`,
      method: 'POST',
      data: formData,
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
  }

  /**
   * 批量导出客户
   */
  async batchExport(data: {
    customerIds: number[]
    fields: string[]
    format: 'excel' | 'csv'
    includeOperationLogs: boolean
  }): Promise<ApiResponse<{ downloadUrl: string; taskId: string }>> {
    return request({
      url: `${this.baseUrl}/batch/export`,
      method: 'POST',
      data
    })
  }

  /**
   * 批量更新客户状态
   */
  async batchUpdateStatus(data: {
    customerIds: number[]
    customerStatus: string
    changeReason: string
  }): Promise<ApiResponse<{ successCount: number; failedCount: number }>> {
    return request({
      url: `${this.baseUrl}/batch/status`,
      method: 'PUT',
      data
    })
  }
}

// 导出API实例
export const customerAPI = new CustomerAPI()

// 导出便捷方法
export default {
  // 客户基础操作
  getList: (params?: CustomerListQuery) => customerAPI.getCustomerList(params),
  getDetail: (id: number) => customerAPI.getCustomerDetail(id),
  create: (data: CreateCustomerRequest) => customerAPI.createCustomer(data),
  update: (id: number, data: UpdateCustomerRequest) => customerAPI.updateCustomer(id, data),
  delete: (id: number, reason: string) => customerAPI.deleteCustomer(id, reason),

  // 标签操作
  getTags: (id: number) => customerAPI.getCustomerTags(id),
  addTags: (id: number, tags: Array<Pick<CustomerTag, 'category' | 'name' | 'value' | 'isSystem'>>) => customerAPI.addCustomerTags(id, tags),
  deleteTag: (id: number, tagId: number) => customerAPI.deleteCustomerTag(id, tagId),

  // 偏好信息
  getPreferences: (id: number) => customerAPI.getTravelPreferences(id),
  updatePreferences: (id: number, data: TravelPreferences) => customerAPI.updateTravelPreferences(id, data),

  // 健康信息
  getHealth: (id: number) => customerAPI.getHealthInfo(id),
  updateHealth: (id: number, data: HealthInfo & { changeReason?: string }) => customerAPI.updateHealthInfo(id, data),

  // 家庭信息
  getFamily: (id: number) => customerAPI.getFamilyInfo(id),
  updateFamily: (id: number, data: FamilyInfo) => customerAPI.updateFamilyInfo(id, data),

  // 操作记录
  getLogs: (id: number, params?: any) => customerAPI.getOperationLogs(id, params),

  // 统计分析
  getStatistics: () => customerAPI.getStatisticsOverview(),
  getTrends: (params?: any) => customerAPI.getStatisticsTrends(params),

  // 批量操作
  batchImport: (file: File, template: string) => customerAPI.batchImport(file, template),
  batchExport: (data: any) => customerAPI.batchExport(data),
  batchUpdateStatus: (data: any) => customerAPI.batchUpdateStatus(data)
}